﻿using FirstFloor.ModernUI.Windows.Controls;
using System;
using System.Net;
using System.Net.Sockets;
using System.Windows;
using System.Windows.Controls;
using Vtron.LEDCorrective.Infrastructure;

namespace Vtron.LEDCorrective.Pages
{
    /// <summary>
    /// NetworkSetting.xaml 的交互逻辑
    /// </summary>
    public partial class NetworkSetting : UserControl
    {
        public NetworkSetting()
        {
            InitializeComponent();

            ip_txt.Text = Utils.IP;
            port_txt.Text = Utils.COMMANDPORT.ToString();
            ipCtroller_txt.Text = Utils.IPCtroller;
            portCtroller_txt.Text = Utils.CTROLLERPORT.ToString();
        }

        private void connect_btn_Click(object sender, RoutedEventArgs e)
        {
            Utils.IP = ip_txt.Text;
            if (!Int32.TryParse(port_txt.Text, out Utils.COMMANDPORT))
            {
                ModernDialog.ShowMessage("端口必须为整数，请重新输入！", "提示", MessageBoxButton.OK);
                return;
            }

            TcpClient socket = new TcpClient();
            IPAddress ipAddress = IPAddress.Parse(Utils.IP);
            try
            {
                socket.Connect(ipAddress, Utils.COMMANDPORT);
            }
            catch
            {
                ModernDialog.ShowMessage("连接VLED发送器失败，请确认输入正确的Ip地址和端口！", "错误", MessageBoxButton.OK);
                return;
            }
            finally
            {
                socket.Close();
            }

            ModernDialog.ShowMessage("连接VLED发送器成功！", "信息", MessageBoxButton.OK);
        }

        private void connectCtroller_btn_Click(object sender, RoutedEventArgs e)
        {
            Utils.IPCtroller = ipCtroller_txt.Text;
            if (!Int32.TryParse(portCtroller_txt.Text, out Utils.CTROLLERPORT))
            {
                ModernDialog.ShowMessage("端口必须为整数，请重新输入！", "提示", MessageBoxButton.OK);
                return;
            }

            TcpClient socket = new TcpClient();
            IPAddress ipAddress = IPAddress.Parse(Utils.IPCtroller);
            try
            {
                socket.Connect(ipAddress, Utils.CTROLLERPORT);
            }
            catch
            {
                ModernDialog.ShowMessage("连接视屏信号控制器失败，请确认输入正确的Ip地址和端口！", "错误", MessageBoxButton.OK);
                return;
            }
            finally
            {
                socket.Close();
            }

            ModernDialog.ShowMessage("连接视屏信号控制器成功！", "信息", MessageBoxButton.OK);
        }
    }
}
